package com.fliad.ai.controller;

import com.fliad.ai.dto.DocumentUploadRequest;
import com.fliad.ai.dto.DocumentUploadResponse;
import com.fliad.ai.entity.AiDocument;
import com.fliad.ai.service.AiDocumentService;
import org.noear.snack.ONode;
import org.noear.solon.ai.rag.Document;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Result;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class AiDocumentController {

    @Inject
    AiDocumentService aiDocumentService;

    @Get
    @Mapping("/documentTypes")
    public Result<List<String>> getDocumentTypes() {
        return Result.succeed(aiDocumentService.getDocumentTypes());
    }

    @Post
    @Mapping("/document")
    public Result<Boolean> create(@Body AiDocument document) throws SQLException {
        return Result.succeed(aiDocumentService.create(document), "新增成功");
    }

    @Post
    @Mapping("/preview")
    public Result<List<Document>> preview(DocumentUploadRequest request) throws SQLException, Exception {
        // 确保预览方法能够正确处理请求并返回结果
        List<Document> previewResult = aiDocumentService.preview(request);
        return Result.succeed(previewResult, "预览成功");
    }

    @Post
    @Mapping("/upload")
    public Result<List<Document>> upload(DocumentUploadRequest request) throws SQLException, Exception {
        return Result.succeed(aiDocumentService.upload(request));
    }

    @Get
    @Mapping(value = "/{id}")
    public Result<DocumentUploadResponse> get(@Path("id") Long id, Context context) throws SQLException, Exception {
        return Result.succeed(aiDocumentService.get(id));
    }

    @Get
    @Mapping("")
    public Result<List<AiDocument>> list(String title, String documentType, Long knowledgeId) throws SQLException {
        return Result.succeed(aiDocumentService.list(title, documentType, knowledgeId));
    }

    @Delete
    @Mapping("/{id}")
    public Result<Boolean> delete(@Path("id") Long id) throws SQLException, IOException {
        return Result.succeed(aiDocumentService.delete(id), "删除成功");
    }

    @Get
    @Mapping("/search/{id}")
    public Result<ONode> search(@Path("id") Long id, @Param String keyword) throws SQLException, Exception {
        return Result.succeed(ONode.newObject().set("searchResult", ONode.load(aiDocumentService.search(id, keyword))));
    }

}
